const express = require("express");
const router = express.Router();
const multipart = require("connect-multiparty");
const multipartMiddleware = multipart();
const Qiniu = require("../../../utils/qiniu");
const fs = require("fs");
router.use(multipart({ uploadDir: __dirname + "/tempfile" }));
router.post("/upload", multipartMiddleware, async (req, res) => {
  // BUG : 当上传多个文件时，有些文件不能删除干净
  let { body, files } = req;
  let { use, dir } = body;
  let user = req.$user
  let file = files.file;

  use = Number(use);

  console.log("文件上传接口收到参数");
  console.log({
    files,
    body,
  });

  if (!file) {
    res.send({ code: 300, msg: "缺少文件" });
    return;
  }
  // 文件上传后所处本机位置
  let filepath = file.path;
  if (use < 1 || !use) {
    fs.unlinkSync(filepath);
    res.send({ code: 301, msg: "缺少use参数" });
    return;
  }
  // 存放目录
  let fileSaveQiNiuDir = {
    1: "user_avatar", // 头像
    2: "user_face", // 人脸
    3: "", // 身份证（正面）
    4: "", // 身份证（反面）
    5: "", // 手持身份证
    6: "", // 营业执照
    7: "", // 其他
  };
  // 文件名称
  let filename = `${user}_${fileSaveQiNiuDir[use]}_${file.originalFilename}`;
  //   文件类型
  let filetype = file.headers["content-type"];
  // 文件大小
  let filesize = file.size;
  // 七牛存放目录
  let QiNiuDir = dir ?? fileSaveQiNiuDir[use];
  if (fs.existsSync(filepath)) {
    Qiniu.upload({
      file: filepath,
      name: filename,
      dir: QiNiuDir,
      fileType: filetype,
      size: filesize,
    })
      .then((uploadData) => {
        fs.unlinkSync(filepath);
        let { key, src } = uploadData;
        res.send({
          code: 0,
          msg: "文件上传成功",
          data: { key, src },
        });
      })
      .catch((err) => {
        res.send({ code: err.code, msg: "文件上传失败" });
      });
  }
});
module.exports = router;
